package com.villaday.idf.custom.pop;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model3.HashInfosEntity;
import com.villaday.idf.model3.HashPrice;
import com.villaday.idf.model3.HashStatesEntity;
import com.villaday.idf.model3.StatesPostEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DateUtils;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.PopularUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import razerdp.basepopup.BasePopupWindow;

public class HousePricePop extends BasePopupWindow {

    private Context mContext;
    private OnBtnClickListener onBtnClickListener;
    private EditText mEtHpNum;
    private String timeValue = "";
    private List<String> dates = new ArrayList<>();
    private String mHouseId;
    private LoadingDialog mLoadDialog;
    private Activity mActivity;
    private final TextView mTvHpConfirm;

    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.popular_house_price);
    }

    public HousePricePop(Context context, Activity activity, String houseId, String name, String infoData, String data) {
        super(context);
        mContext = context;
        mActivity = activity;
        PopularUtil.buildAnimal();
        setBackground(0);
        setOutSideDismiss(true);
        setKeepSize(true);
        setPopupFadeEnable(false);
        setBackgroundColor(Color.parseColor("#B3000000"));
        setBlurBackgroundEnable(true);
        mHouseId = houseId;
        TextView tvHpName = findViewById(R.id.tv_hp_name);
        TextView tvHpType = findViewById(R.id.tv_hp_type);
        TextView tvHpTime = findViewById(R.id.tv_hp_time);
        TextView tvHpNotify = findViewById(R.id.tv_hp_notify);

        mEtHpNum = findViewById(R.id.et_hp_num);


        tvHpName.setText(name);

        HashInfosEntity.BodyBean infoBody = new Gson().fromJson(infoData, HashInfosEntity.BodyBean.class);
        tvHpType.setText(infoBody.getSettlementMode());
        tvHpNotify.setText(infoBody.getSettlementModeDesc());


        HashStatesEntity.BodyBean bodyBean = new Gson().fromJson(data, HashStatesEntity.BodyBean.class);
        List<HashStatesEntity.BodyBean.MonthsBean> mMonths = bodyBean.getMonths();

        List<HashStatesEntity.BodyBean.MonthsBean.DaysBean> list = new ArrayList<>();
        for (int i = 0; i < mMonths.size(); i++) {
            for (int j = 0; j < mMonths.get(i).getDays().size(); j++) {
                if (!mMonths.get(i).getDays().get(j).getText().equals("default")) {
                    list.add(mMonths.get(i).getDays().get(j));

                    if (mMonths.get(i).getDays().get(j).isSelect()) {
                        dates.add(mMonths.get(i).getDays().get(j).getDate());
                    }
                }
            }
        }

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isSelect()) {
                if (i + 2 < list.size() && list.get(i + 1).isSelect() && list.get(i + 2).isSelect()) {
                    String startData = list.get(i).getDate();
                    String endDate = null;
                    boolean isOk = true;
                    for (int j1 = i; j1 < list.size(); j1++) {
                        if (isOk) {
                            if (!list.get(j1).isSelect()) {
                                i = j1 - 1;
                                endDate = list.get(i).getDate();
                                isOk = false;
                            }

                            if ((j1 == list.size() - 1 && list.get(j1).isSelect())) {
                                i = j1;
                                endDate = list.get(i).getDate();
                                isOk = false;
                            }
                        }
                    }
                    timeValue = timeValue + DateUtils.data2Data(startData) + "—" + DateUtils.data2Data(endDate) + "、";
                } else {
                    timeValue = timeValue + DateUtils.data2Data(list.get(i).getDate()) + "、";
                }
            }
        }


        LogUtil.jLog().e(new Gson().toJson(dates));
        if (timeValue.length() > 1) {
            timeValue = timeValue.substring(0, timeValue.length() - 1);
        }
        tvHpTime.setText(timeValue);
        mEtHpNum.setText("0");


        findViewById(R.id.iv_hp_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mTvHpConfirm = findViewById(R.id.tv_hp_confirm);

        mTvHpConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
                Map<String, Object> map = new HashMap<>();
                HashPrice hashPrice = new HashPrice();
                hashPrice.setMode(3);
                hashPrice.setCostPrice(mEtHpNum.getText().toString());
                hashPrice.setDates(dates);
                LogUtil.jLog().e(new Gson().toJson(hashPrice));
                OkHttpUtil.postJson(mContext, String.format(Constant.URL.hashPrices, SharedPreferencesUtil.getRoleInfoId(mContext), mHouseId), hashPrice, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        try {
                            LogUtil.jLog().e(json);
                            dismissDialog();
                            StatesPostEntity statesPostEntity = new Gson().fromJson(json, StatesPostEntity.class);
                            if (statesPostEntity.getCode().equals(Constant.Strings.SUC)) {
                                ToastUtil.initToast(mContext, "设置成功");
                                onBtnClickListener.onBtnClick(mEtHpNum.getText().toString());
                                dismiss();
//                                PhoneUtil.showOrHide(mContext);
                                PhoneUtil.showOrHide(mContext, (Activity) mContext);
                            } else {
                                ToastUtil.initToast(mContext, statesPostEntity.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });


            }
        });


        mEtHpNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    mTvHpConfirm.setEnabled(true);
                    mTvHpConfirm.setBackgroundResource(R.drawable.shape_fe_ff40);
                } else {
                    mTvHpConfirm.setEnabled(false);
                    mTvHpConfirm.setBackgroundResource(R.drawable.shape_gradient_7f_8e_40);
                }

                if (s.toString().contains(".") && s.toString().split("\\.").length > 1
                        && s.toString().split("\\.")[1].length() > 2) {
                    mEtHpNum.setText(s.toString().split("\\.")[0] + "." + s.toString().split("\\.")[1].substring(0, 2));
                    mEtHpNum.setSelection(mEtHpNum.length());
                }

                if (s.toString().equals(".")) {
                    mEtHpNum.setText("0.");
                    mEtHpNum.setSelection(mEtHpNum.length());
                }

                if (s.length() > 1 && !s.toString().contains(".") && s.toString().substring(0, 1).equals("0")) {
                    mEtHpNum.setText(s.toString().substring(1));
                    mEtHpNum.setSelection(mEtHpNum.length());
                }
            }
        });

    }


    @Override
    protected Animation onCreateShowAnimation() {
        return PopularUtil.ShowAnimation();
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        return PopularUtil.dismissAnimation();
    }

    public void setOnBtnClickListener(OnBtnClickListener onBtnClickListener) {
        this.onBtnClickListener = onBtnClickListener;
    }

    public interface OnBtnClickListener {
        void onBtnClick(String money);
    }


    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadingDialog.newInstance("加载中");
        }
        mLoadDialog.show(mActivity.getFragmentManager(), "loading");
    }


    /**
     * 设置加载框
     */
    protected void dismissDialog() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }
    }


}
